package thread;

/**
 * Created with IntelliJ IDEA
 * Description:死锁最简单的情况：连续对同一个线程进行加锁（重复锁）
 * User:34398
 * Date:2024-07-18
 * Time:10:32
 */


/*下面代码不会四锁，因为synchronized做了特殊处理，如果换成C++或者python就会出问题
* （可重复锁）*/
class Conter1 {
    public int count = 0;

    synchronized public void add() {//可以在类里面用这个关键字修饰方法
        count++;
    }
}

public class DeadLock {

    public static void main(String[] args) throws InterruptedException {
        Conter1 conter = new Conter1();
        Thread thread1 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {

                synchronized(DeadLock.class){//第一次加锁成功
                    conter.add();//第二次对同一个对象进行加锁，就要先等待这个对象解锁，但是这个对象要在31行出来才行，所以他会死锁

                }

            }
        });

        Thread thread2 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                synchronized(DeadLock.class){//第一次加锁成功
                    conter.add();//但是第二次会出现阻塞，导致死锁
                }
            }
        });

        thread1.start();
        thread2.start();
        thread1.join();
        thread2.join();

        System.out.println(conter.count);
    }

    /**
     * Created with IntelliJ IDEA
     * Description:；两个线程两把锁
     * User:34398
     * Date:2024-07-19
     * Time:8:46
     */
    public static class twoLock {

        private static Object locker1 = new Object();
        private static Object locker2 = new Object();

        public static void main(String[] args) {

            Thread thread1 = new Thread(() -> {
                synchronized (locker1) {
                    System.out.println("线程1自枷锁完成");
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    synchronized (locker2) {
                        System.out.println("线程1在加2的锁");
                    }


                }

            });
            Thread thread2 = new Thread(() -> {
                synchronized (locker2) {
                    System.out.println("线程2自加锁完成");
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    synchronized (locker1) {
                        System.out.println("线程2在加1的锁");
                    }

                }
            });



            thread1.start();
            thread2.start();
            System.out.println("shh_");

        }
    }
}

